# 打开摄像头
import cv2
# 引入时间对象
import datetime
# from facenet_pytorch import MTCNN, InceptionResnetV1
import numpy as np

from ExistFace import existFace

def open_camera(username):
    global key, show_frame
    cap = cv2.VideoCapture(0)
    # mtcnn = MTCNN()

    # 设置摄像头的分辨率
    t = 1.5
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, int(800 * t))
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, int(600 * t))

    while True:
        fig,frame = cap.read()
        # 判断摄像头未启动
        if fig is None:
            print("没找到摄像头")
            break
        key = cv2.waitKey(1)
        # 判断此时的frame是否复合要求
        flag = existFace(frame)
        frame = cv2.flip(frame, 1)  # 水平翻转帧，修正摄像头默认的镜像问题
        # _frame = np.array(frame)

        # boxs, scores, points = mtcnn.detect(frame, landmarks=True)

        # 手动退出
        if key == ord(" "):
            break
        elif key == ord("s"):
            if flag :
                time = datetime.datetime.now()
                time = time.strftime("%H%M%S")
                # xxx.拼音名称.jpg
                cv2.imwrite(f"./train/{time}.{username}.jpg",frame)
                print(f"./train/{time}.{username}.jpg")
            else:
                print("capture pic failed")
        # 按下s保存一张照片
        show_frame = frame.copy()
        if flag:
            cv2.circle(show_frame,(50,50),20,color=(0,255,0),thickness=cv2.FILLED)
        else:
            cv2.circle(show_frame,(50,50),20,color=(0,0,255),thickness=cv2.FILLED)
        cv2.putText(show_frame, "Press S to Save", (100, 60), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

        cv2.imshow("capture",show_frame)
        # print(show_frame.shape)

    # 释放资源
    cap.release()
    cv2.destroyAllWindows()
    return show_frame, key

if __name__ == "__main__":
    open_camera("zzz")